package com.h3c.nem.service;

import com.alibaba.fastjson.JSONObject;
import com.h3c.nem.client.DataCenterFeignClient;
import com.h3c.nem.config.TopicRabbitConfig;
import com.h3c.nem.entity.SdNoticeRecord;
import com.h3c.nem.entity.SdOperLog;
import com.h3c.nem.mapper.SdNoticeRecordMapper;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;

@Service
public class ManuTranscationService {

    @Autowired
    DataCenterFeignClient dataCenterFeignClient;

    @Resource
    private ValueOperations<String, Object> valueOperations;

    @Autowired
    CommService commService;

    @Autowired
    SdNoticeRecordMapper sdNoticeRecordMapper;



    @Autowired
    private PlatformTransactionManager transactionManager;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private TopicRabbitConfig topicRabbitConfig;

    public void doSaveInventoryRequestLog(SdOperLog requestLog) {
        requestLog.setAppId("nem-manager");
        Message message = topicRabbitConfig.getMessage(JSONObject.toJSONString(requestLog));
        rabbitTemplate.convertAndSend(topicRabbitConfig.getExchange(), topicRabbitConfig.getOperLogQueue(), message);
    }

    public void doSaveNoticeRecord(SdNoticeRecord sdNoticeRecord) {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);//新发起一个事务
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            sdNoticeRecordMapper.insertSdNoticeRecord(sdNoticeRecord);

            transactionManager.commit(status);
        } catch (Exception e) {
            transactionManager.rollback(status);
        }

    }

}
